using System;
using System.Windows.Input;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Commands;
using Silverlight.Weblog.Client.DAL.Events;
using Silverlight.Weblog.Client.DAL.ViewModel;
using Silverlight.Weblog.Common.IoC;
using Silverlight.Weblog.Server.DAL;
using Silverlight.Weblog.UI.Web.RiaServices;

namespace Silverlight.Weblog.Client.Default.Widgets
{
    public class HeadlineViewModel : ViewModelBase, IHeadlineViewModel, IDisposable
    {
        public HeadlineViewModel()
        {
            IoC.Get<IEventAggregator>().GetEvent<InitiaPayloadLoadedEvent>().Subscribe(UpdateViewModel);

            this.HomeCommand = new DelegateCommand<object>((o) =>
                IoC.Get<IEventAggregator>().GetEvent<NavigateToHomePageEvent>().Publish(Model));
        }

        public void UpdateViewModel(User user)
        {
            this.Model = user;
        }

        public string BlogName
        {
            get
            {
                if (Model == null)
                    return null;

                return Model.BlogName;
            }
        }

        public string BlogSubtitle
        {
            get
            {
                if (Model == null)
                    return null;

                return Model.BlogTitle;
            }
        }


        #region HomeCommand
        private ICommand _homeCommand;
        public ICommand HomeCommand
        {
            get { return _homeCommand; }
            set
            {
                if (_homeCommand != value)
                {
                    _homeCommand = value;
                    RaisePropertyChanged("HomeCommand");
                }

            }
        }
        #endregion HomeCommand

        #region Model
        private User _model;
        public User Model
        {
            get { return _model; }
            set
            {
                if (_model != value)
                {
                    _model = value;
                    RaisePropertyChanged("Model");
                    RaisePropertyChanged((HeadlineViewModel vm) => vm.BlogName);
                    RaisePropertyChanged((HeadlineViewModel vm) => vm.BlogSubtitle);
                }

            }
        }
        #endregion Model

        #region Implementation of IDisposable

        public void Dispose()
        {
            IoC.Get<IEventAggregator>().GetEvent<InitiaPayloadLoadedEvent>().Subscribe(UpdateViewModel);
        }

        #endregion
    }
}